const { Compilation } = require('webpack')
const { ConcatSource } = require("webpack-sources");
module.exports = class InsertBannerLog {
  constructor({banner, style} = {banner: '', style: 'color: #1890ff'}) {
    this.banner = banner
    this.style = style
  }

  apply(compiler) {
    compiler.hooks.thisCompilation.tap('InsertBannerLog', (compilation) => {
      compilation.hooks.processAssets.tap({
        name: 'sourceMapHandle',
        stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
      }, (assets) => {
        const entryNames = Object.keys(compiler.options.entry)
        entryNames.forEach(entryName => {
          const files = compilation.entrypoints.get(entryName).getFiles()
          const entryFileName = files[0]
          // const entryAsset = compilation.getAsset(entryFileName)
          const chunk = compilation.chunks.find((chunk) => chunk.files.includes(entryFileName))
          const banner = compilation.getPath(this.banner, {
            filename: entryFileName,
            chunk
          })
          compilation.updateAsset(entryFileName, (oldSource) => {
            return new ConcatSource(oldSource, '\n', `console.log('%c${banner}', ${this.style})`)
          })
        })
      })
    })
  }
}